//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.group;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.math.BigDecimal;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.me.util.MEDate;
import org.jpgolay.me.util.Parameter;

// Referenced classes of package org.jpgolay.me.group:
//            GroupCRUD, GroupAdvanceSearchGUI, GroupAction
public class GroupController {

    class ListSelectionHandler
            implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (!lsm.isSelectionEmpty()) {
                int minIndex = lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                int size = (maxIndex - minIndex) + 1;
                if (listId != null) {
                    listId = null;
                }
                listId = new String[size];
                int iTabl = 0;
                for (int i = minIndex; i <= maxIndex; i++) {
                    if (lsm.isSelectedIndex(i)) {
                        listId[iTabl] = (String) groupTable.getTable().getValueAt(i, 0);
                    }
                    iTabl++;
                }

            }
        }

        ListSelectionHandler() {
        }
    }

    public GroupController(SearchBox groupSearch, TableViewerS groupTable, LabelDateButton groupExecut, Parameter param, JDesktopPane desktop) {
        this.groupSearch = null;
        this.groupTable = null;
        this.groupExecut = null;
        groupSearchGui = null;
        calendarPeriod = null;
        listId = null;
        write = false;
        this.groupSearch = groupSearch;
        this.groupTable = groupTable;
        this.groupExecut = groupExecut;
        this.param = param;
        this.desktop = desktop;
        date = new MEDate();
        crud = new GroupCRUD();
        initLaw();
        initSearch();
        initTable();
        initExecut();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 29 && param.getAccessLaw().charAt(29) == '1') {
            write = true;
        }
    }

    private void initSearch() {
        groupSearch.setList(new String[]{
                    "Code (client)", "Raison social (client)", "Numero de BL"
                });
        groupSearch.setVal("");
        groupSearch.setAdvanceSearch(getDeliverySearchGUI());
        groupSearch.getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        groupSearch.getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
    }

    private void initTable() {
        groupTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
                });
        groupTable.setListColumnNotEditable(new int[]{
                    0, 1
                });
        groupTable.setCellEditable(false);
        groupTable.setColumnNames(new String[]{
                    "BL", "DATE", "CLIENT", "LIVREUR", "LIVRE LE"
                });
        groupTable.setPreferredColumnSize(new int[]{
                    40, 50, 50, 40, 50
                });
        actionSearch();
    }

    private void initExecut() {
        groupExecut.setLabel("Date");
        groupExecut.setDate(date.getPlain());
        groupExecut.getButton().setEnabled(write);
        groupExecut.getButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionGroupDeliveryNote();
            }
        });
    }

    private GroupAdvanceSearchGUI getDeliverySearchGUI() {
        if (groupSearchGui == null) {
            groupSearchGui = new GroupAdvanceSearchGUI();
            groupSearchGui.setAgency(0);
            groupSearchGui.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriod();
                }
            });
        }
        return groupSearchGui;
    }

    private CalendarPeriod getCalendarPeriod() {
        if (calendarPeriod == null) {
            calendarPeriod = new CalendarPeriod();
            calendarPeriod.setFromDate("01/01/1991");
            calendarPeriod.setToDate("01/01/2090");
            calendarPeriod.getButtonLeft().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodOK();
                }
            });
            calendarPeriod.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodCANCEL();
                }
            });
            calendarPeriod.setLocation(600, 50);
            calendarPeriod.setSize(320, 130);
        }
        return calendarPeriod;
    }

    private void actionSearch() {
        from = getCalendarPeriod().getFromDate();
        to = getCalendarPeriod().getToDate();
        agency = getDeliverySearchGUI().getAgency() + 1;
        StringBuffer sql = new StringBuffer();
        if (groupSearch.getSelectedIndex() == 1) {
            sql.append("SELECT ventes.id, date, raison_sociale, livre, date_livraison FROM ventes, clients ");
        } else {
            sql.append("SELECT id, date, clients_id, livre, date_livraison FROM ventes ");
        }
        sql.append("WHERE prefixe = 'BL'");
        sql.append(" AND no_fact IS NULL");
        if (agency != 6) {
            sql.append(" AND entreprise_id=");
            sql.append(agency);
        }
        sql.append(" AND date BETWEEN '");
        sql.append(date.toMysql(from));
        sql.append("' AND '");
        sql.append(date.toMysql(to));
        switch (groupSearch.getSelectedIndex()) {
            case 0: // '\0'
                if (groupSearch.getVal().equals("")) {
                    sql.append("' ORDER BY clients_id");
                } else {
                    sql.append("' AND clients_id LIKE '");
                    sql.append(groupSearch.getVal());
                    sql.append("%' ORDER BY clients_id");
                }
                break;

            case 1: // '\001'
                if (groupSearch.getVal().equals("")) {
                    sql.append("' AND clients_id=clients.id");
                    sql.append(" ORDER BY raison_sociale");
                } else {
                    sql.append("' AND clients_id=clients.id");
                    sql.append(" AND raison_sociale LIKE '");
                    sql.append(groupSearch.getVal());
                    sql.append("%' ORDER BY raison_sociale");
                }
                break;

            case 2: // '\002'
                if (groupSearch.getVal().equals("")) {
                    sql.append("' ORDER BY id");
                } else {
                    sql.append("' AND id LIKE '");
                    sql.append(groupSearch.getVal());
                    sql.append("%' ORDER BY id");
                }
                break;

            default:
                if (groupSearch.getVal().equals("")) {
                    sql.append("' ORDER BY clients_id");
                } else {
                    sql.append("' AND clients_id LIKE '");
                    sql.append(groupSearch.getVal());
                    sql.append("%' ORDER BY clients_id");
                }
                break;
        }
        Object data[][] = crud.getDataList(sql.toString());
        if (data != null) {
            groupTable.setData(data);
            listSelectionModel = groupTable.getTable().getSelectionModel();
            listSelectionModel.addListSelectionListener(new ListSelectionHandler());
            groupTable.getTable().setSelectionModel(listSelectionModel);
        } else {
            groupTable.setData(getEmptyTable());
        }
    }

    private Object[][] getEmptyTable() {
        Object data[][] = new Object[3][5];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUN";
                data[i][2] = "BL";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
            data[i][4] = null;
        }

        return data;
    }

    private void actionCalendarPeriod() {
        getCalendarPeriod().setVisible(true);
        getCalendarPeriod().toFront();
        desktop.add(getCalendarPeriod(), JLayeredPane.DEFAULT_LAYER);
        try {
            getCalendarPeriod().setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void actionCalendarPeriodOK() {
        getDeliverySearchGUI().setPeriode(getCalendarPeriod().getMessage());
        actionCalendarPeriodCANCEL();
    }

    private void actionCalendarPeriodCANCEL() {
        getCalendarPeriod().setVisible(false);
        desktop.remove(getCalendarPeriod());
    }

    private void actionGroupDeliveryNote() {
        if (listId == null) {
            JOptionPane.showMessageDialog(null, "Aucune selection !");
        } else if (groupExecut.getDate().equals("")) {
            JOptionPane.showMessageDialog(null, "Date Invalide !");
        } else {
            GroupAction ga = new GroupAction();
            ga.setUserId(param.getUserId());
            if (!ga.execute(listId, groupExecut.getDate())) {
                JOptionPane.showMessageDialog(null, "Groupement de BL refus\351 !\nVerifier que tous les BL s\351lectionn\351s\nappartiennent au m\352me client.");
            } else {
                StringBuffer r = new StringBuffer();
                int nbBl = 0;
                for (int i = 0; i < listId.length; i++) {
                    if (listId[i] != null) {
                        r.append("\nNum\351ro de BL " + listId[i]);
                        nbBl++;
                    }
                }

                JOptionPane.showMessageDialog(null, "Groupement de BL ex\351cut\351 avec succ\350s !\nCode client : " + ga.getCustomerId() + "\nNombre de BL regroup\351(s) : " + nbBl + "\nListe des BL regroup\351s : " + r.toString() + "\nSur la facture num\351ro : F " + ga.getSalesBillId() + "\nTotal net \340 payer : " + ga.getTotalNetPrice().setScale(2, 4).toString() + "\u20AC (TTC)");
                listId = null;
                actionSearch();
            }
        }
    }
    private SearchBox groupSearch;
    private TableViewerS groupTable;
    private LabelDateButton groupExecut;
    private GroupAdvanceSearchGUI groupSearchGui;
    private CalendarPeriod calendarPeriod;
    private GroupCRUD crud;
    private JDesktopPane desktop;
    private Parameter param;
    private String from;
    private String to;
    private int agency;
    private MEDate date;
    private String listId[];
    private ListSelectionModel listSelectionModel;
    private boolean write;
}
